/*
 * @FileName: [CompanyController.java] 
 * @Package com.bci.pwtz.controller 
 * 
 * 
 * Copyright (c) 2011-2015 BCINFO Technology Limited Com.
 * All rights reserved.
 * 
 * This software is the confidential and proprietary 
 * information of BCINFO Technology Limited Company
 * ("Confidential Information"). You shall not disclose 
 * such Confidential Information and shall use it only
 * in accordance with the terms of the contract agreement 
 * you entered into with RKY.
 * 
 * $Rev$
 * $LastChangedDate$
 * $LastChangedBy$
 * 
 * @category ALUMNI
 * @version 1.1
 * @author $Author$
 *
 * Change History:[Formatter: author date description] <br/>
 * 1
 * 2
 * 3
*/


package com.bci.pwtz.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bci.pwtz.common.PwtzConstants;
import com.bci.pwtz.common.util.PaginationList;
import com.bci.pwtz.exception.PwtzDatabaseException;
import com.bci.pwtz.exception.PwtzException;
import com.bci.pwtz.mysql.model.Company;
import com.bci.pwtz.mysql.model.CompanyUser;
import com.bci.pwtz.mysql.model.UserCompanyRef;
import com.bci.pwtz.service.CompanyService;
import com.bci.pwtz.service.CompanyUserService;
import com.bci.pwtz.service.MessageService;
import com.bci.pwtz.service.UserCompanyRefService;

/**
 * 一句话描述 <br/>
 * <p>Description:<br/>
 *    <p>TODO 详细描述
 *
 * <p>For Examples <br/>
 * <PRE>
 *      TODO 代码使用示例
 * </PRE>
 * <p>
 */
@Controller
@RequestMapping("/user/company")
public class CompanyController extends AbstractController
{
    @Autowired
    private CompanyService companyService;
    
    @Autowired
    private CompanyUserService companyUserService;
    
    @Autowired
    private UserCompanyRefService refService;
    
    @Autowired
    private MessageService messageService;
    
    @RequestMapping(value="/list",method=RequestMethod.POST)
    @ResponseBody
    public PaginationList<Company> list(String companyName,int pageszie,int pagenum) throws PwtzException{
        
        PaginationList<Company> list = new PaginationList<Company>();
        try
        {
        	//System.out.println("companyName="+companyName);
        	//System.out.println("pageszie="+pageszie);
        	//System.out.println("pagenum="+pagenum);
            list=companyService.findCompany(companyName, pageszie, pagenum);
            //System.out.println("list.getTotalPage()="+list.getTotalPage());
            //System.out.println("list.getTotalRecord()="+list.getTotalRecord());
            long userid = (Long)session.getAttribute("userId");
            //System.out.println("userid="+userid);
            Map<Long,Integer> companyRef = companyUserService.getUserCompanyRef(userid);
            for(int i=0;i<list.getRecords().size();i++){
            	Company company = list.getRecords().get(i);
            	//System.out.println("company.getCompanyId()="+company.getCompanyId());
            	//System.out.println("companyRef.containsKey(company.getCompanyId())="+companyRef.containsKey(company.getCompanyId()));
            	if(companyRef.containsKey(company.getCompanyId())){
            		//System.out.println("companyRef.get(company.getCompanyId())="+companyRef.get(company.getCompanyId()));
            		company.setRefStatus(companyRef.get(company.getCompanyId()));
            	}
            }
        }
        catch (PwtzDatabaseException e)
        {
            e.printStackTrace();
        }
        //System.out.println("list.getRecords().size()="+list.getRecords().size());
        
        return list;
    }
    
    @RequestMapping(value="/add",method=RequestMethod.POST)
    @ResponseBody
    public Map<String, String> add(String companyName,String province,String city,String country,String remark,Long pId,int type){
        Map<String, String> map=new HashMap<String, String>();
        try
        {
            Long userId = getUserId();
            int count = companyService.selectCreateCompanyNumByUserId(userId);
            if(count>=PwtzConstants.MAX_CREATE_COMPANY_COUNT){
                map=packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL,ERROR_VALUE_MSG_TYPE_ERROR,null,"超过创建单位最大数限制");
            }
            count=companyService.selectCompanyCount(pId, companyName);
            if(count!=0){
                map=packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL,ERROR_VALUE_MSG_TYPE_ERROR,null,"创建单位名称重复");
            }
            Company company= new Company();
            company.setCompanyName(companyName);
            company.setProvinceCode(province);
            company.setCityCode(city);
            company.setAreaCode(country);
            company.setRemark(remark);
            company.setCreatorId(userId);
            if(type == 0){
                company.setpId(getLastCompanyId());
            }else{
                company.setpId(pId);
            }
            Company ret=companyService.add(company,type);
            CompanyUser companyUser = companyUserService.load(userId);
            if(type==1){
                session.setAttribute("user", companyUser);
            }
            if(ret!=null){
                map=packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS,ERROR_VALUE_MSG_TYPE_INFO,null,"创建单位成功");
            }else{
                map=packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL,ERROR_VALUE_MSG_TYPE_ERROR,null,"创建单位失败");
            }
        }
        catch (PwtzDatabaseException e)
        {
            map = packageException(e);
        }
        return map;
    }
    
    @RequestMapping(value="/edit",method=RequestMethod.POST)
    @ResponseBody
    public Map<String, String> edit(String companyName,String province,String city,String country,String remark,Long companyId){
        Map<String, String> map=new HashMap<String, String>();
        try
        {
            Company company= new Company();
            company.setCompanyId(companyId);
            company.setCompanyName(companyName);
            company.setProvinceCode(province);
            company.setCityCode(city);
            if(StringUtils.isEmpty(country)){
                country="0";
            }
            company.setAreaCode(country);
            company.setRemark(remark);
            int ret=companyService.update(company);
            if(ret>0){
                map=packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS,ERROR_VALUE_MSG_TYPE_INFO,null,"编辑单位成功");
            }else{
                map=packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL,ERROR_VALUE_MSG_TYPE_ERROR,null,"编辑单位失败");
            }
        }
        catch (PwtzDatabaseException e)
        {
            map = packageException(e);
        }
        return map;
    }
    
    //添加子单位
    @RequestMapping(value="/addChild",method=RequestMethod.POST)
    @ResponseBody
    public Map<String, String> addChild(String companyName,String province,String city,String country,String remark,Long pId,int type){
        Map<String, String> map=new HashMap<String, String>();
        try
        {
            Long userId = getUserId();
            int count = companyService.selectCreateCompanyNumByUserId(userId);
            if(count>=PwtzConstants.MAX_CREATE_COMPANY_COUNT){
                map=packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL,ERROR_VALUE_MSG_TYPE_ERROR,null,"超过创建 子单位最大数限制");
            }
            Company company= new Company();
            company.setpId(pId);
            company.setCompanyName(companyName);
            company.setProvinceCode(province);
            company.setCityCode(city);
            if(StringUtils.isEmpty(country)){
                country="0";
            }
            company.setAreaCode(country);
            company.setRemark(remark);
            company.setCreatorId(userId);
            if(type == 0){
                company.setpId(getLastCompanyId());
            }else{
                company.setpId(pId);
            }
            count=companyService.selectCompanyCount(pId, companyName);
            Company ret=null;
            if(count>0){
                ret=companyService.add(company,type);
            }
            CompanyUser companyUser = companyUserService.load(userId);
            if(type==1){
                session.setAttribute("user", companyUser);
            }
            if(ret!=null){
                map=packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS,ERROR_VALUE_MSG_TYPE_INFO,null,"创建子单位成功");
            }else{
                map=packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL,ERROR_VALUE_MSG_TYPE_ERROR,null,"创建子单位失败");
            }
        }
        catch (PwtzDatabaseException e)
        {
            map = packageException(e);
        }
        return map;
    }
    @RequestMapping(value = "/listsub", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> listsub()
    {
        Map<String,Object> retVal = new HashMap<String,Object>();        
        CompanyUser currentUser = (CompanyUser)session.getAttribute("user");
        long currentCompanyID =currentUser.getLastCompanyId();       
        try
        {
            List<Map<String,Object>> companyChildrens = companyService.findChildrens(currentCompanyID, 0);            
            retVal.put(ERROR_KEY_OP_RESULT, ERROR_VALUE_OP_RESULT_SUCCESS);
            retVal.put("companylist",companyChildrens);
            return retVal;
        }
        catch(Exception e)
        {
            retVal.put(ERROR_KEY_OP_RESULT,ERROR_VALUE_OP_RESULT_FAIL);
            retVal.put(ERROR_KEY_MSG_DESC, "系统异常");
            return retVal;
        }
    }
    
    @RequestMapping(value = "/childrencompany", method = RequestMethod.POST)
    @ResponseBody
    public List<Map<String, Object>> childrenCompany()
    {
        List<Map<String, Object>> retVal = new ArrayList<Map<String,Object>>();        
        if(session.getAttribute("user") == null)
        {
            return retVal;
        }
        CompanyUser user = (CompanyUser)session.getAttribute("user");
        long currentCompanyID =0;
        if(user!=null && user.getLastCompanyId()!=null){
            currentCompanyID = user.getLastCompanyId();
        }
        try
        {
            return companyService.findChildrens(currentCompanyID, 0);            
        }
        catch(Exception e)
        {
            return retVal;
        }
    }
  //查找单位（先查找，在修改）
    @RequestMapping(value = "/load", method = RequestMethod.POST)
    @ResponseBody
      public Company load(Long companyId) throws PwtzException{
        Company company = new Company();
        try{
            if(null!=companyId){
                company=companyService.load(companyId);
            } 
        }
        catch (PwtzDatabaseException e)
        {
            e.printStackTrace();
        }
        return company;
   }
    
    @RequestMapping(value="/mycompany",method=RequestMethod.POST)
    @ResponseBody
    public PaginationList<Company> findMyCompany(int pageSize,int pageNo) throws PwtzException{
        Long userId = getUserId();
        PaginationList<Company> list = new PaginationList<Company>();
        try
        {
            list=companyService.findMyCompany(userId, pageSize, pageNo);
        }
        catch (PwtzDatabaseException e)
        {
            e.printStackTrace();
        }
        return list;
    }
    
    /**
     * 
     * 用户更新公司状态<br/>
     * <p>Description: 调用该controller成功后，页面执行window.location.reload()脚本
     * <br/>
     * <p>Author: dengwj<br/>
     * <p>Date: 2014-10-16-下午8:09:58<br/>
     * <p>
     * @param status
     * @return   
     *
     */
    @RequestMapping(value = "/updatestatus", method = RequestMethod.POST)
    @ResponseBody
    public Map<String,String> updateStatus(int status)
    {
        Map<String, String> respMap = new HashMap<String, String>();
        CompanyUser companyUser = getUser();
        try
        {
            Company updateCompany = new Company();
            updateCompany.setCompanyId(companyUser.getLastCompanyId());
            updateCompany.setStatus(status);
            companyService.update(updateCompany);
            if(session.getAttribute("companyEnable")!=null)
            {
                session.removeAttribute("companyEnable");
            }            
            respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO, null,"操作成功");
        }
        catch (PwtzDatabaseException e)
        {
            respMap = packageUppException(e);
        }
        return respMap;
    }
    
    /**
     * 
     * 用户退出公司 <br/>
     * <p>Description:非ajax调用，直接用post表单到该地址，流程执行完毕后，页面自动重定向到userflow.jsp
     * <br/>
     * <p>Author: dengwj<br/>
     * <p>Date: 2014-10-16-下午8:11:02<br/>
     * <p>
     * @param resp
     * @param companyUserId
     * @param companyId   
     *
     */
    @RequestMapping(value="/exitcompany",method=RequestMethod.POST)
    public void exitCompany(HttpServletResponse resp, long companyUserId,long companyId)
    {
        CompanyUser loginUser = getUser();        
        if(companyId != loginUser.getLastCompanyId())
        {
            _log.error("exitCompany|退出单位不是当前单位");
            return;
        }
        Company lastCompany = null;
        try
        {
            lastCompany = companyService.load(companyId);
        }
        catch (PwtzDatabaseException e)
        {
            _log.error("exitCompany|"+ExceptionUtils.getStackTrace(e));
            return;
        }
        if(lastCompany == null)
        {
            _log.error("exitCompany|退出单位时当前单位对象不存在");
             return;
        }
        
        if(lastCompany.getCreatorId() == companyUserId)
        {
            _log.error("exitCompany|不能退出自己创建的单位");
            return;
        }
        
        try
        {
          //删除用户与单位角色的关系
            companyUserService.clearUserRoleRef(companyUserId, companyId);
            
            //删除用户与单位的关系
            companyUserService.deleteRef(companyUserId, companyId);
            
            //设置用户的最后操作单位为null
//            CompanyUser newUser = new CompanyUser();
//            newUser.setCompanyUserId();
//            newUser.setLastCompanyId(null);
            companyUserService.exitCompany(loginUser.getCompanyUserId());            
        }
        catch (PwtzDatabaseException e)
        {
            _log.error("exitCompany|"+ExceptionUtils.getStackTrace(e));
        }
        
      //设置session中的用户最后操作单位为null
        loginUser.setLastCompanyId(null);
        session.setAttribute("user", loginUser);
        
        //移除session中用户的超级管理员标识和权限数据和当前公司状态标识
        session.removeAttribute("isSuper");
        session.removeAttribute("actionCodes");
        session.removeAttribute("companyEnable");
//        String path=session.getServletContext().getContextPath();
        String path="/";
        try
        {
            List<UserCompanyRef> list=refService.findUserCompanyRefList(companyUserId);
            if(null!=list && list.size()>0){
                resp.sendRedirect(path+"/user/m/switch.jsp");
            }else{
                resp.sendRedirect(path+"/user/m/userflow.jsp"); 
            }
        }
        catch (PwtzDatabaseException e1)
        {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        //重定向到userflow.jsp
        
        catch (IOException e)
        {
            _log.error("exitCompany|"+ExceptionUtils.getStackTrace(e));
        }
    }
    @RequestMapping(value="/del",method=RequestMethod.POST)
    @ResponseBody
    public Map<String,String> del(Long companyId){
        Map<String,String> map=new HashMap<String, String>();
        try{
            if(companyId==null||companyId==0){
                map=packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_INFO, null, "公司id错误");
            }else{
                int result=companyService.delete(companyId);
                if(result>0){
                    map=packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO, null, "操作成功");
                    Company company=companyService.load(companyId);
                    if(company!=null){
                        messageService.sendNoticeSmsAndMsg(getUserId(), "你已经退出了{0}单位，客户端请重新登录", company.getCompanyName());
                    }
                }else{
                    map=packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_INFO, null, "操作失败");
                }
            }
        }catch(Exception e){
            _log.error("del"+ExceptionUtils.getStackTrace(e));
        }
        return map;
    }
}
